// JavaScript Document

////////////////////////////////////////////////////////////////////////////////////
//xc
PJS.xc = function(){
	this.uid = PJS.rand("pjs_xc");
	this.depth = 0;
	this.response_errors = ["400","401","402","403","404","500","501","502","503"];
	
	this._uri = PJS.BASE_URL+"wsc.php";
	this._type = "POST";//POST,GET
	this._debug = false;
	this._cursor = "wait";
	this._status = "1";
	
	this._POST = "POST";
	this._GET = "GET";
	
	this._mpf = "wsc_";
	
	this.loadingFunction = function(){};
	this.doneLoadingFunction = function(){};
	this.loadingTimeout = null;
};
PJS.xc.prototype.init = function(){
	
};
PJS.xc.prototype.debug = function(text){
	alert(text);
};
PJS.xc.prototype.status = function(text){
	window.status = text;
};
PJS.xc.prototype.getRequestObject = function(){
	//Get the XMLHttpRequest Object
	if(this._debug) this.debug("Initializing Request Object..");
	var req = null;
	if(typeof XMLHttpRequest != "undefined")
		req = new XMLHttpRequest();
	if(!req && typeof ActiveXObject != "undefined"){
		try{
			req=new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			try{
				req=new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e2){
				try {
					req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
				}catch (e3){
					req=null;
				}
			}
		}
	}
	if(!req && window.createRequest)
		req = window.createRequest();
	if(!req) this.debug("Request Object Instantiation failed.");
	return req;
};
PJS.xc.prototype.objectToXML = function(obj){
	// Generates an XML message that  can understand from a javascript object
	var sXml = "<obj>";
	for(i in obj){
		try{
			if(i == 'constructor')
				continue;
			if(obj[i] && typeof(obj[i]) == 'function')
				continue;
				
			var key = i;
			var value = obj[i];
			if(value && typeof(value)=="object" && this.depth <= 50){
				this.depth++;
				value = this.objectToXML(value);
				this.depth--;
			}
			
			sXml += "<e><k>"+key+"</k><v>"+value+"</v></e>";
		}
		catch(e)
		{
			if(this._debug) this.debug(e.name+": "+e.message);
		}
	}
	sXml += "</obj>";

	return sXml;
};
PJS.xc.prototype.call = function(m,args,type,url){
	// Sends a XMLHttpRequest to call the specified PHP function on the server
	// * type is optional -- defaults to POST
	var i,r,post_data;
	if(document.body && this._cursor)
		document.body.style.cursor = 'wait';
	this.status('Sending Request...');
	clearTimeout(this.loadingTimeout);
	this.loadingTimeout = setTimeout("pjs_xc.loadingFunction();",400);
	if(this._debug) this.debug("Starting ...");
	
	//type
	if(type == null){
	   var request_type = this._POST;
	}
	else {
		var request_type = type;
	}
	//var uri = this._uri;
	if(typeof(url) == "undefined"){
		var uri = this._uri;
	} else {
		var uri = PJS.BASE_URL + url;
	}
	
	//
	var value;
	switch(request_type)
	{
		case this._GET:{
			var uriGet = uri.indexOf("?")==-1?"?xc="+encodeURIComponent(m):"&xc="+encodeURIComponent(m);
			if(args){
				for(i = 0; i<args.length; i++)
				{
					value = args[i];
					if(typeof(value)=="object")
						value = this.objectToXML(value);
					uriGet += "&xcargs[]="+encodeURIComponent(value);
				}
			}
			uriGet += "&xcr=" + new Date().getTime();
			uri += uriGet;
			post_data = null;
			} break;
		case this._POST:{
			post_data = "xc="+encodeURIComponent(m);
			post_data += "&xcr="+new Date().getTime();
			if(args){
				for(i = 0; i <args.length; i++)
				{
					value = args[i];
					if(typeof(value)=="object")
						value = this.objectToXML(value);
					post_data = post_data+"&xcargs[]="+encodeURIComponent(value);
				}
			}
			} break;
		default:
			alert("Illegal request type: " + request_type); return false; break;
	}
	
	//
	r = this.getRequestObject();
	if(!r) return false;
	r.open(request_type==this._GET?"GET":"POST",uri,true);
	if(request_type == this._POST)
	{
		try
		{
			r.setRequestHeader("Method","POST " + uri + " HTTP/1.1");
			r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		}
		catch(e)
		{
			alert("Your browser does not appear to  support asynchronous requests using POST.");
			return false;
		}
	};
	r.onreadystatechange = function()
	{
		if(r.readyState != 4)
			return;
		
		if(r.status==200)
		{
			if(this._debug) this.debug("Received:\n" + r.responseText);
			if(r.responseXML && r.responseXML.documentElement)
				pjs_xc.processResponse(r.responseXML);
			else {
				var errorString = "Error: the XML response that was returned from the server is invalid.";
				errorString += "\nReceived:\n" + r.responseText;
				trimmedResponseText = r.responseText.replace( /^\s+/g,"" );// strip leading space
				trimmedResponseText = trimmedResponseText.replace( /\s+$/g,"" );// strip trailing
				if(trimmedResponseText != r.responseText)
					errorString += "\nYou have whitespace in your response.";
				alert(errorString);
				document.body.style.cursor = 'default';
				pjs_xc.status('Invalid XML response error');
			}
		}
		else {
			if(this.responseErrorsForAlert.containsValue(r.status)){
				var errorString = "Error: the server returned the following HTTP status: " + r.status;
				errorString += "\nReceived:\n" + r.responseText;
				alert(errorString);
			}
			document.body.style.cursor = 'default';
			pjs_xc.status('Invalid XML response error');
		}
		
		delete r;
		r = null;
	};
	
	//
	if(this._debug) this.debug("Calling "+m +" uri="+uri+" (post:"+ post_data +")");
	r.send(post_data);
	this.status('Waiting for data...');
	delete r;
	return true;
};
PJS.xc.prototype.processResponse = function(xml){
	//Process XML Responses returned from the request
	clearTimeout(this.loadingTimeout);
	this.doneLoadingFunction();
	this.status('Processing...');
	var tmp = null;
	xml = xml.documentElement;
	if(xml == null)
		return;
	
	for(var i=0; i<xml.childNodes.length; i++){
		var cmd;
		var id;
		var property;
		var data;
		var search;
		var call;
		var before;
		var objElement = null;
		
		for(var j=0; j<xml.childNodes[i].attributes.length; j++)
		{
			if(xml.childNodes[i].attributes[j].name == "n")
			{
				cmd = xml.childNodes[i].attributes[j].value;
			}
			else if(xml.childNodes[i].attributes[j].name == "t")
			{
				id = xml.childNodes[i].attributes[j].value;
			}
			else if(xml.childNodes[i].attributes[j].name == "p")
			{
				property = xml.childNodes[i].attributes[j].value;
			}
			else if(xml.childNodes[i].attributes[j].name == "c")
			{
				call = xml.childNodes[i].attributes[j].value;
			}
		}
		
		//
		if(xml.childNodes[i].childNodes.length > 1 && xml.childNodes[i].firstChild.nodeName == "#cdata-section")
		{
			data = "";
			for(var j=0; j<xml.childNodes[i].childNodes.length; j++)
			{
				data += xml.childNodes[i].childNodes[j].data;
			}
		}
		else if(xml.childNodes[i].childNodes.length > 1)
		{
			for(var j=0; j<xml.childNodes[i].childNodes.length; j++)
			{
				if(xml.childNodes[i].childNodes[j].childNodes.length > 1 && xml.childNodes[i].childNodes[j].firstChild.nodeName == "#cdata-section")
				{
					var internalData = "";
					for(var k=0; k<xml.childNodes[i].childNodes[j].childNodes.length;k++)
					{
						internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue;
					}
				} else {
					var internalData = xml.childNodes[i].childNodes[j].firstChild.nodeValue;
				}
			
				if(xml.childNodes[i].childNodes[j].nodeName == "s")
				{
					search = internalData;
				}
				if(xml.childNodes[i].childNodes[j].nodeName == "r")
				{
					data = internalData;
				}
			}
		}
		else if(xml.childNodes[i].firstChild)
			data = xml.childNodes[i].firstChild.nodeValue;
		else
			data = "";
		
		//
		var cmdFullname;
		try
		{
			if(cmd=="alert"){
				alert(data);
			} else if(cmd=="assign"){
				objElement = PJS.$(id);
				if(objElement && property){
					eval("objElement."+property+"=data;");
				}
			} else if(cmd=="call"){
				if(call.substring(0,5) == 'this.'){
					eval(call+"('"+data+"')");
				} else if	(typeof(call) == 'function'){
					call(data);
				}
			}
		} 
		catch(e)
		{
			if(this._debug)
				alert("While trying to '"+cmdFullname+"' (command number "+i+"),the following error occured:\n"
					+ e.name+": "+e.message+"\n"
					+ (id&&!objElement?"Object with id='"+id+"' wasn't found.\n":""));
		}
		
		//
		delete objElement;
		delete cmd;
		delete cmdFullname;
		delete id;
		delete property;
		delete search;
		delete data;
		delete call;
		delete before;
		delete internalData;
		delete j;
		delete k;
	}
	delete xml;
	delete i;
	document.body.style.cursor = 'default';
	this.status('Done');
};
PJS.xc.prototype.getForm = function(form){
	if(typeof(form) == "string"){
		form = document.forms[form];	
	}
	if(form && form.tagName && form.tagName == 'FORM'){
		return form	;
	}
	return null;
};
PJS.xc.prototype.getFormValues = function(frm){
	var objForm;
	var submitDisabledElements = false;
	if(arguments.length > 1 && arguments[1] == true)
		submitDisabledElements = true;
	var prefix="";
	if(arguments.length > 2)
		prefix = arguments[2];
	
	if(typeof(frm) == "string")
		objForm = PJS.$(frm);
	else
		objForm = frm;
	var sXml = "";
	if(objForm && objForm.tagName == 'FORM')
	{
		var formElements = objForm.elements;
		for( var i=0; i<formElements.length; i++)
		{
			if(!formElements[i].name)
				continue;
			if(formElements[i].name.substring(0,prefix.length) != prefix)
				continue;
			if(formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
				continue;
			if(formElements[i].disabled && formElements[i].disabled == true && submitDisabledElements == false)
				continue;
			var name = formElements[i].name;
			if(name)
			{
				if(sXml != '')
					sXml += '&';
				if(formElements[i].type=='select-multiple')
				{
					for(var j = 0; j<formElements[i].length; j++)
					{
						if(formElements[i].options[j].selected == true)
							sXml += name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";
					}
				}
				else
				{
					sXml += name+"="+encodeURIComponent(formElements[i].value);
				}
			} 
		}
	}
	
	sXml +="";
	
	return sXml;
};
PJS.xc.prototype.postForm = function(form,m){
	var form = this.getForm(form);
	if(form){
		if(!form.id){
			form.setAttribute("id",PJS.rand("form_"));	
		}
		var fvs = this.getFormValues(form.id);
		if(typeof(m)=="undefined"){
			m = "home";
		}
		m = this._mpf + m;
		this.call(m,['form',fvs]);
	}
};
PJS.xc.prototype.postFormC = function(form){
	this._uric = this._uri;
	this._uri = document.location.href;
	this.postForm(form);
	this._uri = this._uric;
};
PJS.xc.prototype.get = function(m,args){
	this.call(m,args);
};
PJS.xc.prototype.widget = function(args){
	this.call('widget',args);
};
//
var pjs_xc = new PJS.xc();
//